package megrez.keycloak.providers.mqtt;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.regex.Pattern;

import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.keycloak.util.JsonSerialization;

import lombok.experimental.UtilityClass;

/**
 * 工具
 *  
 * @author Lucky Yang
 * @since 2.6.9
 */
@UtilityClass
public class MqttUtils {
    private static final Pattern SPECIAL_CHARACTERS = Pattern.compile("[^*#a-zA-Z0-9 _/-]");
	private static final Pattern SPACE = Pattern.compile(" ");

    /**
     * 创建JSON格式的Mqtt消息
     * @param message
     * @param qos
     * @param retained
     * @return
     * @throws IOException
     */
    public MqttMessage buildJsonMqttMessage(Object message, int qos, boolean retained) throws IOException {
        final String json = JsonSerialization.writeValueAsPrettyString(message);
        MqttMessage payload = new MqttMessage(json.getBytes(StandardCharsets.UTF_8));
        payload.setQos(qos);
        payload.setRetained(retained);
        return payload;
    }

    public String normalizeTopic(CharSequence topic) {
		return SPACE.matcher(SPECIAL_CHARACTERS.matcher(topic).replaceAll(""))
				.replaceAll("_");
	}
}
